package com.qingzhuge.web.interceptor;

import com.qingzhuge.common.utils.IpUtils;
import com.qingzhuge.common.utils.TimeUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author : zero.xiao
 * @description : 日志拦截器
 * @date :2018/5/9 0009 下午 17:12
 * @modified :
 */
@Component
public class EventInterceptor extends Interceptor {
    private final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("ThreadLocalStartTime");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String path = request.getServletPath();
        logger.debug("request start， IP:{}, Method:{}, URI:{}", IpUtils.getIpAddr(request), request.getMethod(), path);
        // 开始时间（该数据只有当前请求的线程可见）
        startTimeThreadLocal.set(System.currentTimeMillis());
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(final HttpServletRequest request, HttpServletResponse response, Object handler,
                                final Exception ex) throws Exception {
        final Long startTime = startTimeThreadLocal.get();
        final Long endTime = System.currentTimeMillis();
        final long runTime = endTime - startTime;
        String path = request.getServletPath();
        // 保存日志
        if (handler instanceof HandlerMethod) {
            String userAgent = request.getHeader("USER-AGENT");
            UserAgent ua = new UserAgent(userAgent);
            OperatingSystem system = ua.getOperatingSystem();
            Browser browser = ua.getBrowser();
            logger.info("path:{},runTime:{},OsName:{},browser:{}", path, runTime, system.getName(), browser.getName());
        }
        logger.debug("ST:{};ET:{};UT:{}ms;URI:{}; ", TimeUtil.date2LocalDate(startTime), TimeUtil.date2LocalDate(endTime), runTime, path);
        startTimeThreadLocal.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
